package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.concurrent.Future;

@Service
public class MyService {
    @Async//开启了另外一个线程
    public void sendSMS() throws Exception {
        System.out.println("调用短信验证码业务方法...");
        long startTime = System.currentTimeMillis();
        Thread.sleep(5000);
        long endTime = System.currentTimeMillis();
        System.out.println("短信业务执行完成耗时：" + (endTime - startTime));
    }


    @Async
//   Future表示一个可能还没有完成的异步任务的结果，
// 针对这个结果可以添加Callback以便在任务执行成功或失败后作出相应的操作。
    public Future<Integer> processA() throws Exception {
        System.out.println("开始分析并统计业务A数据...");
        Long startTime = System.currentTimeMillis();
        Thread.sleep(4000);
        int count = 123456;
        Long endTime = System.currentTimeMillis();
        System.out.println("业务A数据统计耗时：" + (endTime - startTime));
        return new AsyncResult<Integer>(count);
    }

    @Async
//Future表示一个可能还没有完成的异步任务的结果，
    public Future<Integer> processB() throws Exception {
        System.out.println("开始分析并统计业务B数据...");
        Long startTime = System.currentTimeMillis();
        Thread.sleep(5000);
        int count = 654321;
        Long endTime = System.currentTimeMillis();
        System.out.println("业务B数据统计耗时：" + (endTime - startTime));
        return new AsyncResult<Integer>(count);
    }


    @Scheduled(cron = "0 00 00 10 09 ?") // 1月8日 凌晨1点 35分 26秒
    public String schedulTask() {
        System.out.println("12345");
        return "12345";
    }

    @Scheduled(fixedDelay = 5000)
    public String schedulTaskForfixedDelay() {
        System.out.println("schedulTaskForfixedDelay");
        return "schedulTaskForfixedDelay";
    }

    @Scheduled(initialDelay = 10000, fixedDelay = 1000 * 60 * 60 * 24)
    public String schedulTaskForinitialDelay() throws Exception {

        System.out.println("schedulTaskForinitialDelay");
        return "schedulTaskForinitialDelay";
    }


    @Autowired
    JavaMailSenderImpl javaMailSender;
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送简单的文本邮件 SimpleMailMessage
     *
     * @param to
     * @param subject
     * @param text
     * @param cc
     * @return
     */
    //可变参数放到参数列表的末尾
    public String sendSimpleMail(String to, String subject,
                                 String text, String... cc) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        message.setCc(cc);
        try {
            javaMailSender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "发送完成";

    }

    /**
     * 发送复杂邮件
     * 1,要求邮件正文，带图片躲着多媒体
     * 2，邮件带附件
     *
     * @param to
     * @param subject
     * @param text
     * @param filepath
     * @param recid
     * @param recPath
     * @return
     */
    public String sendMimeMail(String to, String subject,
                               String text, String filepath,
                               String recid, String recPath
    ) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        StringBuilder sb = new StringBuilder();
        sb.append(text);
        text += "<img src='cid:" + recid + "'/></body></html>";
        helper.setText(text, true);
        //静态资源
        FileSystemResource res = new FileSystemResource(new File(recPath));
        helper.addInline(recid, res);
        //附件
        FileSystemResource file = new FileSystemResource(new File(filepath));
        String fileName = filepath.substring(filepath.lastIndexOf("\\"));
        helper.addAttachment(fileName, file);
        javaMailSender.send(message);
        return "发送成功";
    }


}
